import random
import threading
from common.logger import logger

accounts_write_lock = threading.RLock()


class AccountService:
    def __init__(self) -> None:
        self._accounts = []
        self._invalid_accounts = []
        self._index = 0
        self._is_active = False
        self._task_id = None
        
    def set_task_id(self, task_id):
        self._task_id = task_id

    def lock(self):
        return accounts_write_lock

    def add(self, account):
        with accounts_write_lock:
            self._accounts.append(account)

    def _clear(self):
        self._accounts.clear()
        self._index = 0

    def invalid(self, account) -> bool:
        with accounts_write_lock:
            if account in self._accounts:
                self._accounts.remove(account)
                self._invalid_accounts.append(account)
                return True
            return False

    def count(self):
        with accounts_write_lock:
            return len(self._accounts)

    def take(self):
        with accounts_write_lock:
            if not self._accounts:
                return None
            self._index += 1
            if self._index >= len(self._accounts):
                self._index = 0
            return self._accounts[self._index]

    def active(self):
        self._is_active = True
